/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[RadioButtonComponent.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package swing.components;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;

/**
 * Swing单选按钮组件
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class RadioButtonComponent {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				RadioButtonFrame frame = new RadioButtonFrame();
				frame.setVisible(true);
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			}
		});
	}
}

class RadioButtonFrame extends JFrame {

	private static final long serialVersionUID = -93786144656166587L;
	private static final int DEFAULT_SIZE = 12;

	private ButtonGroup buttonGroup = null;
	private JPanel buttonPanel = null;

	private JLabel mainLabel = null;

	public RadioButtonFrame() {
		setTitle("Radio Test");
		this.setSize(500, 200);
		setLocationByPlatform(true);
		setResizable(false);

		mainLabel = new JLabel("Hello Java World", SwingConstants.CENTER);

		buttonGroup = new ButtonGroup();
		buttonPanel = new JPanel();

		generateRadioButton("Small Size", 8);
		generateRadioButton("Medium Size", 12);
		generateRadioButton("Large Size", 18);
		generateRadioButton("Extra Large", 24);

		getContentPane().add(mainLabel, BorderLayout.CENTER);
		getContentPane().add(buttonPanel, BorderLayout.SOUTH);
	}

	/**
	 * 构造JRadio对象
	 * 
	 * @param radioName
	 *            radio的名称
	 * @param fontSize
	 *            字体的大小
	 */
	private void generateRadioButton(String radioName, final int fontSize) {
		boolean selected = (fontSize == DEFAULT_SIZE);

		JRadioButton radioButton = new JRadioButton(radioName, selected);
		// 要把RadioButton加入到ButtonGroup
		buttonGroup.add(radioButton);
		buttonPanel.add(radioButton);

		ActionListener listener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				String family = mainLabel.getFont().getFamily();
				mainLabel.setFont(new Font(family, Font.BOLD, fontSize));
			}
		};

		radioButton.addActionListener(listener);
	}
}
